const reqlib = require('app-root-path').require
const Proxy = require('../../proxy')
const { numberUtil } = require('../../util')
const binanceProxy = reqlib('/app/common/binanceProxy')

const BtbIndex = Proxy.BtbIndex
const Dictionary = Proxy.Dictionary
const QuoteVolume = Proxy.QuoteVolume
const AssetRecordProxy = Proxy.AssetRecord

// 获取我的账户信息
module.exports = async function () {
  const queryData = await Promise.all([
    Dictionary.find({
      key: {
        $in: [
          'btbPositionConfig', 'btbStrategy', 'btbLeverage',
          'btbDoneMessage', 'btbOpen', 'btbErrorEmail', 'preFindBtbResult', 'findBtbResult'
        ]
      }
    }),
    // 合约账户
    binanceProxy.getFuturesAccount(),
    // 汇率
    // axios({
    //   method: 'get',
    //   url: `https://push2.eastmoney.com/api/qt/stock/get?secid=133.USDCNH&ut=f057cbcbce2a86e2866ab8877db1d059&forcect=1&fields=f43&invt=2&cb=jQuery18302206528858403829_1652938694805&wbp2u=|0|0|0|wap&_=1652938775453`
    // }).then((data) => {
    //   let str = data.data.slice(data.data.indexOf('(') + 1, data.data.lastIndexOf(')'))
    //   let list = JSON.parse(str).data
    //   return list['f43'] || 0
    // }),
    // 自动的
    BtbIndex.find({
      status: 1,
      hy_status: 1,
      // 执行自动的
      manual: 0
    }, {
      sort: '-proportion',
      lean: true
    }),
    // 手动的
    BtbIndex.find({
      // 执行自动的
      manual: 1
    }, {
      sort: '-proportion',
      lean: true
    }),
    QuoteVolume.find({}, {
      // 12小时
      limit: 48,
      sort: '-time'
    }),
    QuoteVolume.find({}, {
      // 12小时
      limit: 96,
      sort: '-time'
    }),
    AssetRecordProxy.find({}, {
      skip: 0,
      limit: 1,
      sort: '-date'
    })
  ])
  const dictionary = queryData[0]
  const futuresAccount = queryData[1]
  // const hl = queryData[2]
  const autoList = queryData[2]
  const manualList = queryData[3]
  const quoteVolumeList = queryData[4]
  const quoteVolume24List = queryData[5]
  const sumList = [...autoList, ...manualList]
  const preAssetList = queryData[6] || []
  const sumSymbolList = []
  sumList.forEach((v, index) => {
    v.reason_list = v.reason_list || []
    v.symbol = `${v.code}USDT`
    let sellReasonCount = 0
    v.reason_list.forEach((t) => {
      t = t || ''
      if (t.startsWith('sellIfOnlyPingByReason-')) {
        sellReasonCount++
      }
    })
    v.buy_sell_analysis_result = undefined
    sumList[index] = {
      code: v.code,
      symbol: v.symbol,
      positionInfo: futuresAccount.positionMap[v.symbol],
      direction: v.direction,
      direction_level: v.direction_level,
      keep_days: v.keep_days,
      leverage: v.leverage,
      manual: v.manual,
      name: v.name,
      now_position_amt: v.now_position_amt,
      now_position_usdt: v.now_position_usdt,
      now_position_cost_price: v.now_position_cost_price,
      stop_profit_price: v.stop_profit_price,
      now_usdt: v.now_usdt,
      ping_next_k: v.ping_next_k,
      ping_next_1hk: v.ping_next_1hk,
      add_times: v.add_times,
      max_all15m_times: v.max_all15m_times,
      strategy: v.strategy,
      strategy_result: v.strategy_result || '',
      max_income_rate: v.max_income_rate || 0,
      price_change_percent: v.price_change_percent || 0,
      quote_volume: v.quote_volume || 0,
      register_usdt_010: v.register_usdt_010 || 0,
      register_usdt_015: v.register_usdt_015 || 0,
      register_usdt_020: v.register_usdt_020 || 0,
      blacklist: v.blacklist || 0,
      sellReasonCount,
      _id: v._id
    }
    sumSymbolList.push(v.symbol)
  })
  const hasPositionSymbolList = futuresAccount.hasPositionSymbolList.filter((v) => {
    return sumSymbolList.indexOf(v) === -1
  })
  const hasPositionList = hasPositionSymbolList.map((symbol) => {
    return {
      symbol: symbol,
      positionInfo: futuresAccount.positionMap[symbol]
    }
  })
  let sumQuoteVolume = 0
  quoteVolumeList.forEach((v) => {
    sumQuoteVolume += v.value
  })
  let sumQuoteVolume24 = 0
  quoteVolume24List.forEach((v) => {
    sumQuoteVolume24 += v.value
  })
  return {
    dictionary: dictionary.map((v) => {
      let value = v.value
      if (['btbDoneMessage', 'preFindBtbResult', 'findBtbResult'].indexOf(v.key) !== -1) {
        try {
          value = JSON.parse(value)
        } catch (e) {
          value = {}
        }
      }
      if (['btbErrorEmail', 'btbOpen'].indexOf(v.key) !== -1) {
        value = value === 'true'
      }
      return {
        key: v.key,
        value: value
      }
    }),
    // 汇率
    // hl: parseFloat(hl) / 10000,
    sumList,
    hasPositionList,
    totalInitialMargin: futuresAccount.totalInitialMargin,
    totalWalletBalance: futuresAccount.totalWalletBalance,
    totalUnrealizedProfit: futuresAccount.totalUnrealizedProfit,
    totalMarginBalance: futuresAccount.totalMarginBalance,
    availableBalance: futuresAccount.availableBalance,
    totalPositionInitialMargin: futuresAccount.totalPositionInitialMargin,
    totalPositionBalance: futuresAccount.totalPositionBalance,
    avQuoteVolume: numberUtil.keepTwoDecimals(sumQuoteVolume / quoteVolumeList.length),
    sumQuoteVolume24: numberUtil.keepTwoDecimals(sumQuoteVolume24 / quoteVolume24List.length),
    preAsset: preAssetList[0] || {}
  }
}
